Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




count( ) FUNCTION


count( ) Function


The count( ) Function is used to count, how many times a substring is present in the String.


Example :


x = "Hello Beautiful World"
y = x.count("Beautiful")
print("The count of the substring is ",y)


Output :



  The count of the substring is 1

In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.


x = "Hello Beautiful World"

java_Collections

And we would be searching the substring 'Beautiful', and count how many times it is present in the String, 'Hello Beautiful World'.


So, we have used the 'count()' Function to count for the substring 'Beautiful'.


y = x.count("Beautiful")

And in this case the substring 'Beautiful' is present just once. So, we got the count as 1.


And the count (i.e. 1) is stored in variable 'y'.


java_Collections

And thus prints the position.


print("The count of the substring is ",y)

Output :



  The count of the substring is 1

Now, let us say you have the below String,


"The Beautiful world is Beautiful indeed"

So there are two occurrence of 'Beautiful'.


Also let us specify the range as second and third paraemeter.


Let us see with the below example.


Example :


x = "The Beautiful world is Beautiful indeed"
y = x.count("Beautiful", 1, 35)
print("The count of the substring is ",y)


Output :



  The count of the substring is 2

In the above code, we have declared a String 'The Beautiful world is Beautiful indeed' and assigned it to a variable 'x'.


x = "The Beautiful world is Beautiful indeed"

java_Collections

And we would be searching the substring 'Beautiful', and count how many times it is present in the String, 'The Beautiful world is Beautiful indeed'.


So, we have used the 'x.count("Beautiful", 1, 35)' Function to count for the substring 'Beautiful'.


And also specified range of 1 to 35, to check how many times the substring 'Beautiful' is present in that range.


y = x.count("Beautiful", 1, 35)

And in this case the substring 'Beautiful' is present twice. So, we got the count as 2.


And the count (i.e. 2) is stored in variable 'y'.


java_Collections

And thus prints the position.


print("The count of the substring is ",y)

Output :



  The count of the substring is 2